/* ******************************************** */
/* * Histogramiser                            * */
/* * Authors: André Bannwart Perina           * */
/* *          Antonio Canabrava Fraideinberze * */
/* *          Willian Felipe Lopes da Silva   * */
/* ******************************************** */

#include <errno.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
	if(4 != argc) {
		fprintf(stderr, "Usage: %s filesPrefix outputFile amount\n", argv[0]);
		return EXIT_FAILURE;
	}

	int i;
	/* Number of files */
	int n = atoi(argv[3]);
	/* Time fitness value */
	int tVal;
	/* Distance fitness value, final fitness value */
	double dVal, fVal;

	/* Mount fileName */
	char *fileName = malloc((strlen(argv[1]) + ((int) log10(n)) + 2) * sizeof(char));

	FILE *ipf;
	/* Open output file */
	FILE *opf = fopen(argv[2], "w");

	/* Error opening file */
	if(NULL == opf) {
		fprintf(stderr, "%s: %s: %s\n", argv[0], strerror(errno), argv[2]);
		return EXIT_FAILURE;
	}

	/* Random seed */
	srand(time(NULL));

	for(i = 0; i < n; i++) {
		/* Open file */
		sprintf(fileName, "%s%d", argv[1], i);
		ipf = fopen(fileName, "r");

		/* Error opening file */
		if(NULL == ipf) {
			fprintf(stderr, "%s: %s: %s\n", argv[0], strerror(errno), fileName);
			return EXIT_FAILURE;
		}

		/* Read fitness values and close file */
		fscanf(ipf, "%d %lf", &tVal, &dVal);
		fclose(ipf);

		/* Calculate final value */
		fVal = tVal * dVal;

		/* Print info. */
		printf("File %d with value %lf\n", i, fVal);

		/* Save winner to output file */
		fprintf(opf, "%d %lf\n", i, fVal);
	}

	/* Free everything */
	free(fileName);
	fclose(opf);

	return EXIT_SUCCESS;
}
